package com.zhang.framelib.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.util.Assert;

import com.zhang.framelib.common.CommonConstants;

/**
 * bean工具  直接使用复制的
 * Title:BeanUtil
 * Description:
 * @Edit_Description:cuishuaiming
 * @version:zhang-framelib 1.0
 */
public class BeanUtil {
	/**
     * 给对象字段为null的设置默认值
     * @param source 对象
     * @Edit_Description:
     * @Create_Version:shebao-framelib 1.0
     */
    public static void setDefProperties(Object source) {
        Assert.notNull(source, "Source must not be null");
        setDefProperties(source, (String[]) null);
    }

    /**
     * 给对象字段为null的设置默认值
     * @param source 对象
     * @param ignoreProperties 忽略设置默认值的字段
     * @Edit_Description:
     * @Create_Version:shebao-framelib 1.0
     */
    public static void setDefProperties(Object source, String... ignoreProperties) {
        Field[] fields = source.getClass().getDeclaredFields();
        List<String> ignoreList = getIgnoreList(ignoreProperties);
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                Object value = field.get(source);
                String type = field.getType().toString();
                if (value != null || ignoreList.contains(name)) {
                    continue;
                }
                if (type.endsWith("String")) {
                    field.set(source, CommonConstants.STRING_DEF);
                } else if (type.endsWith("Integer")) {
                    Integer defInt = CommonConstants.INTEGER_DEF;
                    if ("priority".equals(name)) {
                        defInt = CommonConstants.PRIORITY_DEF;
                    }
                    field.set(source, defInt);
                } else if (type.endsWith("Date")) {
                    field.set(source, CommonConstants.DATE_DEF);
                } else if (type.endsWith("BigDecimal")) {
                    field.set(source, CommonConstants.DECIMAL_DEF);
                }
            }
        } catch (Exception ep) {
            ep.printStackTrace();
        }
    }
    
    /**
     * 获取忽略设置默认值的字段
     * @param ignoreProperties 字段数组
     * @Edit_Description:
     * @Create_Version:shebao-core-model 1.0
     */
    private static List<String> getIgnoreList(String... ignoreProperties) {
        List<String> ignoreList = new ArrayList<String>();
        ignoreList.add("id");
        ignoreList.add("serialVersionUID");
        if (ignoreProperties != null) {
            ignoreList.addAll(Arrays.asList(ignoreProperties));
        }
        return ignoreList;
    }
}
